package com.aduerr.v1shouyin.mvp.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.PreAuthoCompleteEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.MoneyTextWatcher;
import com.aduerr.v1shouyin.util.NumUtil;
import com.aduerr.v1shouyin.util.ToastUtils;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.math.BigDecimal;
import java.util.HashMap;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/4/15 18:21
 * @change
 * @chang time
 * @class describe
 */

public class PreAuthoCompleteActivity extends AppCompatActivity {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_goods_money)
    TextView tvGoodsMoney;
    @BindView(R.id.tv_deposit)
    TextView tvDeposit;
    @BindView(R.id.et_used_money)
    EditText etUsedMoney;
    @BindView(R.id.tv_refund_money)
    TextView tvRefundMoney;
    @BindView(R.id.tv_beizhu_calculator)
    TextView tvBeizhuCalculator;
    @BindView(R.id.ll_notify)
    LinearLayout llNotify;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.bt_confirm)
    Button btConfirm;
    @BindView(R.id.ll_deposit)
    LinearLayout llDeposit;

    private double goodsMoney, deposit;
    private String orderId;
    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_authon_complete);
        ButterKnife.bind(this);
        tvTitle.setText("预授权完成");
        goodsMoney = getIntent().getDoubleExtra("goods_money", 0);
        deposit = getIntent().getDoubleExtra("deposit", 0);
        orderId = getIntent().getStringExtra("order_id");
        if(deposit == 0) {
            llDeposit.setVisibility(View.GONE);
        } else {
            llDeposit.setVisibility(View.VISIBLE);
        }
        tvGoodsMoney.setText("￥" + NumUtil.formatFloat(goodsMoney + deposit));
        tvDeposit.setText("￥" + deposit);
//        tvRefundMoney.setText("￥" + deposit);
        etUsedMoney.addTextChangedListener(new MoneyTextWatcher(etUsedMoney));
    }

    @OnClick({R.id.img_back, R.id.bt_confirm})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.bt_confirm:
                if(TextUtils.isEmpty(etUsedMoney.getText())) {
                    ToastUtils.showToast(this, "请输入预授权完成金额");
                    return;
                }
                preAuthoComplete();
                break;
        }
    }

    @OnTextChanged(value = R.id.et_used_money, callback =
            OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void afterTextChanged(Editable s) {
        if(TextUtils.isEmpty(s)) {
//            tvRefundMoney.setText("￥" + deposit);
            return;
        }
        if(s.toString().equals(".")) return;
        double money = Double.parseDouble(s.toString());
        double total =
                new BigDecimal(deposit).add(new BigDecimal(goodsMoney)).setScale(2,
                        BigDecimal.ROUND_HALF_UP).doubleValue();

        if(money > total) {
            etUsedMoney.setText(NumUtil.formatFloat(deposit + goodsMoney));
            etUsedMoney.setSelection(NumUtil.formatFloat(deposit + goodsMoney).length());
            return;
        }
        tvRefundMoney.setText("￥" + NumUtil.formatFloat(goodsMoney + deposit - money));

    }

    private void preAuthoComplete() {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OrderID", orderId);
        addParams.put("Remark", etRemark.getText().toString());
        addParams.put("ConsumeMoney",
                NumUtil.formatFloat(Double.parseDouble(etUsedMoney.getText().toString())));

        APIRetrofit.getAPIService().preAuthoComplete(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PreAuthoCompleteEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(loadingDialog == null) {
                            loadingDialog =
                                    new ProgressDialog(PreAuthoCompleteActivity.this,
                                            ProgressDialog.STYLE_SPINNER);
                            loadingDialog.setTitle("正在操作中");
                            loadingDialog.setCanceledOnTouchOutside(false);
                        }
                        loadingDialog.show();
                    }

                    @Override
                    public void onNext(@NonNull PreAuthoCompleteEntity entity) {
                        //                        if (Tools.isAvailable
                        //                        (acquirePayEntity)) return;
                        if(entity.getSuccess() == 1) {
                            Intent intent = new Intent(PreAuthoCompleteActivity.this,
                                    PreAuthoOrderActivity.class);
                            intent.putExtra("orderid", orderId);
                            intent.putExtra("tag", "result");
                            startActivity(intent);
                            finish();
                        } else {
                            ToastUtils.showToast(PreAuthoCompleteActivity.this,
                                    entity.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(loadingDialog != null && loadingDialog.isShowing())
                            loadingDialog.dismiss();
                        ToastUtils.showToast(PreAuthoCompleteActivity.this, "网络异常");
                    }

                    @Override
                    public void onComplete() {
                        if(loadingDialog != null && loadingDialog.isShowing())
                            loadingDialog.dismiss();
                    }
                });


    }
}
